import json

from tortoise import Tortoise

from app.model import mysql
from app.settings.config import DEFAULT_AVATAR, QINIU_MEDIA_HOST


async def get_user_info(user_id: int):
    """
    获取用户信息
    :param user_id: 用户编号
    :return: {}
    """
    user_info = await mysql.UserInfo.get_or_none(id=user_id)
    return user_info


async def get_user_base_info(user_id: int):
    """
    获取用户基本信息：编号，头像，昵称
    :param user_id:
    :return:
    """
    return await mysql.User.get_or_none(id=user_id)


def format_avatar_url(avatar):
    """
    格式化头像链接
    :param avatar:
    :return:
    """
    avatar = avatar.strip()
    if not avatar:
        return DEFAULT_AVATAR
    if avatar.startswith('http'):
        return avatar
    return f'{QINIU_MEDIA_HOST}/{avatar}?imageMogr2/auto-orient/thumbnail/!375x375r/sharpen/1/gravity/Center/crop/375x375/format/jpg'


async def get_user_custom_tags(user_id: int):
    """
    获取用户自定义标签
    :param user_id: 用户编号
    :return: []
    """
    user_info = await get_user_info(user_id)
    custom_tags = []
    if user_info and user_info.custom_tags:
        try:
            custom_tags = json.loads(user_info.custom_tags)
        except Exception as e:
            custom_tags = []
    return custom_tags


async def add_user_custom_tags(user_id: int, tags: list):
    """
    新增自定义标签
    :param user_id: 用户编号
    :param tags: 新增的一组标签
    :return:
    """
    if not tags:
        return
    custom_tags = await get_user_custom_tags(user_id)
    custom_tags_set = set(custom_tags)
    is_change = False
    for tag in tags:
        if not tag:
            continue
        if tag not in custom_tags_set:
            custom_tags.insert(0, tag)
            is_change = True
    if is_change:
        await mysql.UserInfo.filter(id=user_id).update(custom_tags=json.dumps(custom_tags, ensure_ascii=False))


async def get_history_search_words(user_id: int):
    """
    获取用户历史搜索词
    :param user_id:
    :return:
    """
    s = await mysql.UserSearch.get_or_none(id=user_id)
    if not s:
        return []
    return json.loads(s.words) if s.words else []


async def empty_history_search_words(user_id: int):
    """
    清空用户历史搜索词
    :param user_id:
    :return:
    """
    await mysql.UserSearch.filter(id=user_id).update(words='')


async def get_follow_status(from_user_id, to_user_id):
    """
    关注状态
    :param from_user_id:
    :param to_user_id:
    :return:
    """
    c = await mysql.Follow.filter(user_id=from_user_id, follow_user_id=to_user_id).count()
    return c > 0
